from django.shortcuts import render
from django.http import HttpResponse

from myapp.models import Stu
from django.contrib.auth.models import User, Permission
from django.contrib.auth import authenticate
from django.contrib.auth.hashers import make_password
from django.shortcuts import render, redirect, reverse
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

# Create your views here.


def index(request):
    return render(request, 'index.html')


def stu(request):
    stu = Stu.objects.all()
    print(stu)

    return HttpResponse("ok")


def register(request):
    '''
    注册表单
    '''
    return render(request, "register.html")


def update(request):
    '''
    提交注册
    '''

    name = request.POST.get("username")
    passwd = request.POST.get("password")
    check_passwd = request.POST.get("check_password")
    print("name:%s,password:%s" % (name, passwd))

    exist = User.objects.filter(username=name)
    if exist:
        return HttpResponse("用户已经存在")

    if passwd != check_passwd:
        return HttpResponse("密码不相同，请重新输入")

    # hash_password = make_password(passwd)
    user = User.objects.create_user(
        username=name,
        password=passwd

    )

    user.save()
    # 注册成功
    return redirect("/login")


def login(request):
    return render(request, "login.html")


def dologin(request):
    username = request.POST.get("username")
    password = request.POST.get("password")

    print("username，password", username, password)
    exist = User.objects.filter(username=username).exists()

    if not exist:
        return redirect("/login?error = 用户不存在")

    user = authenticate(username=username, password=password)

    if user:
        # 登录成功 跳转到stulist页面
        return redirect("/stuPage")
    else:
        return redirect("/login?error = 密码错误")

    return redirect("/login")


def stuPage(request):
    stuList = Stu.objects.all()
    paginator = Paginator(stuList, 5)  # 每页显示10个学生
    page = request.GET.get('page', 1)
    try:
        students = paginator.get_page(page)
    except PageNotAnInteger:
        # 如果页码不是整数，返回第一页的数据
        students = paginator.get_page(1)
    except EmptyPage:
        # 如果页码超出范围，返回最后一页的数据
        students = paginator.get_page(paginator.num_pages)
    return render(request, "studentList.html", {"stuList": students})


def demo(request):
    '''状态保持'''
    # session设置
    # request.session['username'] = '556677'

    # session获取
    # name = request.session.get("username",default=None)
    # print(name)
    # session删除

    # 删除单个key 不存在时报错
    # del request.session['a']

    # 清除所有会话,但不会删除数据
    request.session.clear()

    # 删除当前的会话数据
    # request.session.flush()
    return HttpResponse("测试状态保持")
